<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../node_modules/lodash/lodash.min.js"></script>
  <style>
    #box {
      width: 500px;
      height: 260px;
      background-color: teal;
      margin: 100px auto;
    }
  </style>
</head>

<body>
  <div id="box"></div>
  <script>
    // 持续触发也执行，只不过执行的频率变低了
    // #1
    // let bBar = true
    // box.addEventListener('mousemove', function (e) {
    //   // #2
    //   /* if (bBar) {
    //     // #3
    //     bBar = false
    //     setTimeout(() => {
    //       const disX = e.pageX - this.offsetLeft
    //       const disY = e.pageY - this.offsetTop

    //       this.innerHTML = `x: ${disX}, y: ${disY}`
    //       // #4
    //       bBar = true
    //     }, 500)
    //   } */

    //   if (!bBar) return
    //   // #3
    //   bBar = false
    //   setTimeout(() => {
    //     const disX = e.pageX - this.offsetLeft
    //     const disY = e.pageY - this.offsetTop

    //     this.innerHTML = `x: ${disX}, y: ${disY}`
    //     // #4
    //     bBar = true
    //   }, 500)
    // })

    function throttle(callback, time) {
      // #1
      let bBar = true
      return function (...args) {
        // #2
        if (!bBar) return
        // #3
        bBar = false
        setTimeout(() => {
          // callback.call(this, ...args)
          callback.apply(this, args)
          // #4
          bBar = true
        }, time);
      }
    }

    box.addEventListener('mousemove', _.throttle(function (e) {
      const disX = e.pageX - this.offsetLeft
      const disY = e.pageY - this.offsetTop
      this.innerHTML = `x: ${disX}, y: ${disY}`
    }, 500))

  </script>
</body>

</html>